package com.atguigu.tingshu.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SearchReceiver {
    @Autowired
    private SearchService searchService;


    /**
     * @author gengjian
     * @date 2025/02/27 16:28:02
     * 上架
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void upperAlbum(Long albumId, Message message, Channel channel){
        //判断用户id
        try {
            if (albumId != null){
                //调用服务层方法
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("消费异常" + e.getMessage());
            System.out.println(e.getMessage());
        }
        //手动确认签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * @author gengjian
     * @date 2025/02/27 16:28:02
     * 下架
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void lowerAlbum(Long albumId, Message message, Channel channel){
        //判断用户id
        try {
            if (albumId != null){
                //调用服务层方法
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("消费异常" + e.getMessage());
            System.out.println(e.getMessage());
        }
        //手动确认签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
